import React from "react";
import {useAuth} from "../context/authContext";
import {Button, Form, Input} from 'antd'
import {useAsync} from "../utils/use-async";

export const LoginScreen = ({onError} : {onError:(error:Error) => void}) =>{

    const {login, user} = useAuth()
    const {run, isLoading} = useAsync()


    const handleSubmit = async (value: {username:string, password:string}) =>{
        await run(login(value)).catch((e) => {onError(e)})
    }
    return <Form onFinish={handleSubmit}>
        {
            user ? <div >登录成功，用户名：{user.name},token:{user.token}</div> : null
        }
        <Form.Item name={'username'} rules={[{required:true, message:'请输入用户名'}]}>
            <Input placeholder={'用户名'} type={"text"} id={"username"}/>
        </Form.Item>
        <Form.Item name={'password'} rules={[{required:true, message:'请输入密码'}]}>
            <Input placeholder={'密码'} type={"password"} id={"password"}/>
        </Form.Item>
        <Form.Item>
            <Button loading = {isLoading} htmlType={"submit"} type={"primary"}>登录</Button>
        </Form.Item>

    </Form>
}